package com.ansuenjob.util;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

public final class NewHttpRequestClient {
	
	/**
	 * 发送传送xml数据
	 * @param path 请求的路径
	 * @param xml 要发送xml数据
	 * @return 是否请求成功
	 * @throws Exception
	 */
	public static boolean postXML(String path, String xml) throws Exception{
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//要发送的实体数据
		byte[] entityData = xml.getBytes();
		conn.setRequestMethod("POST");
		conn.setReadTimeout(5*1000);
		conn.setDoOutput(true);//如果通过post提交数据，必须设置允许对外输出数据
		/**
		 * 以下两个是必须的投字段
		 */
		conn.setRequestProperty("Content-Type","text/xml; charset=UTF-8 ");
		conn.setRequestProperty("Content-Length", String.valueOf(entityData.length));
		
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(entityData);
		outputStream.flush();
		outputStream.close();
		
		if(conn.getResponseCode() == 200){
			conn.disconnect();
			return true;
		}else{
			conn.disconnect();
			return false;
		}
	}
	
	/**
	 * 通过get方式向服务器发出请求
	 * @param path 请求的路径
	 * @param requestParams 请求参数
	 * @return 是否请求成功
	 * @throws Exception
	 */
	public static byte[] get(String path, Map<String, String> requestParams) throws Exception{
		
		
		requestParams.put("dataParam", String.valueOf(new Date().getTime()));
		
		
		StringBuilder stringBuilder = new StringBuilder(path);
		stringBuilder.append("?");
		for (Map.Entry<String, String> entry : requestParams.entrySet()) {
			stringBuilder.append(entry.getKey())
			             .append("=").append(entry.getValue()).append("&");
		}
		stringBuilder.deleteCharAt(stringBuilder.length()-1);
		
		URL url = new URL(stringBuilder.toString());
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setReadTimeout(5*1000);
		byte[] data = null;
	    if(conn.getResponseCode() == 200){
	    	InputStream inputStream = conn.getInputStream();
	    	data = StreamTool.readDataFromStream(inputStream);
	    	inputStream.close();
	    	conn.disconnect();
	    }else {
	    	conn.disconnect();
	    	throw new RuntimeException("响应错误，responseCode为：" + conn.getResponseCode() );
	    } 
		return data;
	}
	
	/**
	 * 通过Post方式向服务器发出请求
	 * @param path 请求的路径
	 * @param requestParams 请求参数
	 * @return 是否请求成功
	 * @throws Exception
	 */
	public static ReturnMessage post(String path, Map<String, String> requestParams) throws Exception{
		
//		Log.i(DazhewangApplication.TAG, "URL:" + getEntityData(path, requestParams));
		ReturnMessage message = null;
		StringBuilder stringBuilder = new StringBuilder();
		if(requestParams != null && !requestParams.isEmpty()){
			for (Map.Entry<String, String> entry : requestParams.entrySet()) {
				stringBuilder.append(entry.getKey())
				.append("=").append(entry.getValue()).append("&");
			}
			stringBuilder.deleteCharAt(stringBuilder.length()-1);
		}
		
		byte[] entityData = stringBuilder.toString().getBytes();
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setReadTimeout(10*1000);
		conn.setDoOutput(true);//如果通过post提交数据，必须设置允许对外输出数据
		/**
		 * 一下两个是必须的投字段
		 */
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", String.valueOf(entityData.length));
		
		/**
		 * 获取conn的输出流
		 */
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(entityData);
		outputStream.flush();
		outputStream.close();
		
		byte[] data = null;
	    if(conn.getResponseCode() == 200){
	    	message = new ReturnMessage();
	    	InputStream inputStream = conn.getInputStream();
	    	data = StreamTool.readDataFromStream(inputStream);
	    	message.obj = data;
	    	message.messageStr = conn.getHeaderField("Date");
	    	inputStream.close();
	    	conn.disconnect();//释放网络连接
	    	return message;
	    }else {
	    	conn.disconnect();
	    	throw new RuntimeException("响应错误，responseCode为：" + conn.getResponseCode() );
	    } 
		
	}
	
	
	/**
	 * path 是请求的主机地址
	 * requestParams 请求的参数
	 * @param charSet 字符集
	 * @return 返回的是一个returnmessage  里面包含一个String 服务器时间   还有一个object对象 在这个方法里面可以强置转型为JsonArray
	 */
	public static ReturnMessage postForJsonArrayWithDate(String path, Map<String, String> requestParams,String charSet) throws Exception {
		ReturnMessage message = post( path, requestParams);
		String dataStr = new String((byte[])message.obj,charSet);
		JSONArray jsonArray = new JSONArray(dataStr);
		message.obj = jsonArray;
		return message;
	}
	
	/**
	 * path 是请求的主机地址
	 * requestParams 请求的参数
	 * @param charSet 字符集
	 * @return 返回的是一个returnmessage  里面包含一个String 服务器时间   
	 * 还有一个object对象 在这个方法里面可以强置转型为JsonObject 我们返回的最终的page对象用JSON输出就是一个JsonObject对象
	 * 
	 */
	public static ReturnMessage postForJsonObjectWithDate(String path, Map<String, String> requestParams,String charSet) throws Exception {
		ReturnMessage message = post(path, requestParams);
		System.out.println(((byte[])message.obj).length);;
		String dataStr = new String((byte[])message.obj,charSet);
		JSONObject jsonObject = new JSONObject(dataStr);
		message.obj = jsonObject;
		return message;
	}
	
	/**
	 * 见postForJsonArrayWithDate 如果服务器压缩数据使用这个方法
	 * @param path
	 * @param requestParams
	 * @return
	 * @throws Exception
	 */
	public static ReturnMessage postForJsonArrayWithDateDepress(String path, Map<String, String> requestParams,String charSet) throws Exception {
		ReturnMessage message = post( path, requestParams);
		byte[] data = (byte[])message.obj;
		byte[] deCepreddData = Compress.byteDecompress(data);
		String dataStr = new String(deCepreddData,charSet);
		JSONArray jsonArray = new JSONArray(dataStr);
		message.obj = jsonArray;
		return message;
	}
	
	/**
	 * 见postForJsonObjectWithDate 如果服务器压缩数据使用这个方法
	 * @param path
	 * @param requestParams
	 * @return
	 * @throws Exception
	 */
	public static ReturnMessage postForJsonObjectWithDateDecompress(String path, Map<String, String> requestParams,String charSet) throws Exception {
		ReturnMessage message = post( path, requestParams);
		byte[] data = (byte[])message.obj;
		System.out.println(data.length);
		byte[] deCepreddData = Compress.byteDecompress(data);
		String dataStr = new String(deCepreddData,charSet);
		JSONObject jsonObject = new JSONObject(dataStr);
		message.obj = jsonObject;
		return message;
	}
	
	private static String  getEntityData(String  path, Map<String, String> requestParams){
		StringBuilder stringBuilder = new StringBuilder(path);
		stringBuilder.append("?");
		for (Map.Entry<String, String> entry : requestParams.entrySet()) {
			stringBuilder.append(entry.getKey())
			             .append("=").append(entry.getValue()).append("&");
		}
		stringBuilder.deleteCharAt(stringBuilder.length()-1);
		return stringBuilder.toString();
	}
}
